<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    width="500"
    :before-close="() => cancel()"
  >
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
    >
      <el-form-item label="字典类型" prop="dictName">
        <el-input v-model="ruleForm.dictName" />
      </el-form-item>
      <el-form-item label="字典类型编码" prop="dictType">
        <el-input v-model="ruleForm.dictType" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="() => cancel()">取 消</el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          保 存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { dictAddDictType, dictUpdateDictType } from '@/api/system';

const { item, type } = defineProps(['type', 'item']);
const emit = defineEmits(['cancel']);

onMounted(() => {
  if (type === 'edit') {
    title.value = '编辑字典类型';
    ruleForm.dictName = item.dictName;
    ruleForm.dictType = item.dictType;
    ruleForm.dictId = item.dictId;
  }
});

const dialogVisible = ref(true);
const title = ref('新增字典类型');
const ruleFormRef = ref();
const ruleForm = reactive({
  dictName: '',
  dictType: '',
});

const rules = reactive({
  dictName: [{ required: true, message: '请输入字典类型', trigger: 'blur' }],
  dictType: [
    { required: true, message: '请输入字典类型编码', trigger: 'blur' },
  ],
});
const submitForm = async (ruleFormRef) => {
  await ruleFormRef.validate((valid) => {
    if (valid) {
      if (type === 'add') {
        dictAddDictType(ruleForm).then(() => {
          cancel(true);
        });
      } else {
        dictUpdateDictType(ruleForm).then(() => {
          cancel(true);
        });
      }
    }
  });
};
const cancel = (flag = false) => {
  emit('cancel', flag);
};
</script>

<style lang="less" scoped>
.search-card,
.table-card {
  margin-bottom: 20px;

  .el-card__header {
    padding: 15px 20px;
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .header-buttons {
    display: flex;
    gap: 10px;
  }
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
